package com.sgcc.manager.sql.util;

import org.w3c.dom.*;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import java.io.File;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.Transformer;

public class AddBook {
    String id = null;
    String title = null;
    String author = null;
    public AddBook(String id, String title, String author) {
        this.id = id;
        this.title = title;
        this.author = author;
    }

    public void add(Document doc) { //这是追加的方法
        Element book = doc.createElement("book");
        Element eid = doc.createElement("id");
        Element etitle = doc.createElement("title");
        Element eauthor = doc.createElement("author");
        Text tid = doc.createTextNode(id);
        Text ttitle = doc.createTextNode(title);
        Text tauthor = doc.createTextNode(author);
        Node nid = book.appendChild(eid).appendChild(tid);
        Node ntitle = book.appendChild(etitle).appendChild(ttitle);
        Node nauthro = book.appendChild(eauthor).appendChild(tauthor);
        Node nbook = doc.getDocumentElement().appendChild(book);

    }

    public void ptintdoc(Document doc) {
        NodeList list = doc.getElementsByTagName("*");
        Element e = null;
        for (int i = 0; i < list.getLength(); i++) {
            e = (Element) list.item(i);
            System.out.println(e.getNodeName() + ":" +
                               e.getFirstChild().getNodeValue());
        }
    }

    public static void main(String[] arg) {
        AddBook addbook = new AddBook("12", "think in java", "tom");
        DocumentBuilderFactory dbfactory = DocumentBuilderFactory.newInstance();
        try {
            DocumentBuilder dbbuilder = dbfactory.newDocumentBuilder();
            Document doc = dbbuilder.parse(new File("D:\\book.xml"));
            addbook.add(doc);
            
            TransformerFactory tff = TransformerFactory.newInstance();
            Transformer tf = tff.newTransformer();

            DOMSource source = new DOMSource(doc);
            StreamResult rs = new StreamResult(new File("D:\\book2.xml"));
            tf.transform(source, rs);

            
            addbook.ptintdoc(doc);
        } catch (Exception ex) {
            System.out.println(ex.toString());
        }
    }

}